#!/usr/bin/env python3
import time
import subprocess
import argparse
from datetime import datetime

# 添加类型提示
from typing import List, Dict

class RedundancyMonitor:
    def __init__(self, ifname: str = 'bond0') -> None:
        # 增加配置验证
        if not os.path.exists(f'/proc/net/bonding/{ifname}'):
            raise FileNotFoundError(f'Bonding interface {ifname} not found')

# 添加异常处理装饰器
def handle_errors(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logging.error(f'Error in {func.__name__}: {str(e)}')
            raise
    return wrapper

    def check_bond_status(self):
        try:
            with open('/proc/net/bonding/bond0') as f:
                status = f.read()
            active = [line.split()[-1] for line in status.splitlines() 
                     if 'Active Slave' in line][0]
            return active
        except Exception as e:
            print(f'监控错误: {e}')
            return None

    def start_monitoring(self):
        prev_active = self.primary
        while True:
            current = self.check_bond_status()
            if current != prev_active:
                switch_time = datetime.now().timestamp() * 1000  # 转换为毫秒时间戳
                if prev_active == self.primary:
                    print(f'主接口故障! 切换时间: {switch_time}')
                else:
                    recovery_delay = (switch_time - self.last_switch).total_seconds()
                    self.results.append(recovery_delay)
                    print(f'网络恢复! 中断时长: {recovery_delay:.4f}秒')
                self.last_switch = switch_time
                prev_active = current
            time.sleep(0.001)  # 将轮询间隔缩短到1ms

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--primary', required=True, help='主网络接口名称')
    parser.add_argument('--secondary', required=True, help='备用网络接口名称')
    args = parser.parse_args()

    monitor = RedundancyMonitor(args.primary, args.secondary)
    try:
        monitor.start_monitoring()
    except KeyboardInterrupt:
        print('\n测试终止，生成报告...')
        with open('switch_metrics.csv', 'w') as f:
            f.write('timestamp,switch_type,latency\n')
            for i, latency in enumerate(monitor.results):
                f.write(f'{i+1},failover,{latency}\n')